using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
using System.Drawing;
using System.Globalization;

namespace Camalon.Drawing
{
	/// <summary>
	/// Summary description for TransparentColorConverter.
	/// </summary>
	public class CompoundColorConverter:ExpandableInstanceConverter
	{
		public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
		{

			if( value is string )
			{
				string colorString = (string)value;

				if( colorString.Length == 0 || string.Compare( colorString, "empty", true, culture)== 0 )
					return CompoundColor.Empty;

				Color c = TransparentColorConverter.FromColorString( colorString );

				
				
				string[] args = colorString.Split(new char[]{';'});

				
				float compound	= 0f;
				string sComp	= null;

				if( args.Length == 3 )		sComp = args[2].Trim();	
				else if( args.Length >= 5 ) sComp = args[4].Trim();	

				if( sComp != null )
				{
					char[] percentChar = culture.NumberFormat.PercentSymbol.ToCharArray();
					string[] _sComp		= sComp.Split(percentChar);	
					sComp				= _sComp[0];

					int compVal	= int.Parse( sComp );
					if( compVal > 100)	compVal = 100;
					if( compVal < 0)	compVal = 0;
					compound = (float)compVal/100f;
				}

				return new CompoundColor( c, compound );

			}
			else

			return base.ConvertFrom (context, culture, value);
		
		}


		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
		{

			if( value is CompoundColor )
			{

				CompoundColor m = (CompoundColor) value;

				if (destinationType == typeof(string)) 
				{
				
					string colorString = TransparentColorConverter.ToColorString( m.Color );
					string percentChar = culture.NumberFormat.PercentSymbol;
					int percent = (int)System.Math.Round( m.CompoundValue * 100f );
					colorString += string.Format(null,"; {0}{1}",percent, percentChar);

					if( colorString.Length == 0) 
						throw base.GetConvertToException( context.PropertyDescriptor.GetValue(context.Instance), destinationType);

					return colorString;

				}
				else if (destinationType == typeof(InstanceDescriptor) ) 
				{

					if( m.CompoundValue == 0f)
					{
						ConstructorInfo ctor = typeof(CompoundColor).GetConstructor(new Type[] {typeof(Color)});
						if (ctor != null) return new InstanceDescriptor(ctor, new object[] {m.Color});
					}
					else
					{
						ConstructorInfo ctor = typeof(CompoundColor).GetConstructor(new Type[] {typeof(Color), typeof( float)});
						if (ctor != null) return new InstanceDescriptor(ctor, new object[] {m.Color, m.CompoundValue});
					}


				}
			}


			return base.ConvertTo (context, culture, value, destinationType);

		}

	}

}
